package wpwork.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import wpwork.base.ActionResult;
import wpwork.base.controller.SuperController;
import wpwork.base.vo.DownloadVO;
import wpwork.entity.GpsInfoEntity;
import wpwork.model.GpsInfoVo;
import wpwork.model.GpsInfoVo2;
import wpwork.permission.entity.UserEntity;
import wpwork.permission.service.UserService;
import wpwork.service.GpsInfoService;
import wpwork.util.JsonUtil;

import javax.validation.Valid;
import java.math.RoundingMode;
import java.util.*;

@RestController
@Tag(name = "示例接口", description = "GpsInfo")
@RequestMapping("/api/example/gpsInfo")
public class GpsInfoController extends SuperController<GpsInfoService, GpsInfoEntity> {

    @Autowired
    private GpsInfoService gpsInfoService;

    @Autowired
    private UserService userService;


    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Operation(summary = "新建或修改")
    @PostMapping
    public ActionResult create(@RequestBody @Valid GpsInfoEntity gpsInfoEntity) {
        GpsInfoEntity entity = JsonUtil.getJsonToBean(gpsInfoEntity, GpsInfoEntity.class);
        gpsInfoService.save(entity);
        if (entity.getDistance() != null) {
            entity.setDistance(entity.getDistance().setScale(1, RoundingMode.HALF_UP));
        }
        String userId = entity.getRemark2();
        UserEntity info = userService.getInfo(userId);
        entity.setRealName(info.getRealName());

        String redisKey = "gps_info:" + entity.getUserid();
        redisTemplate.opsForValue().set(redisKey, entity);

        return ActionResult.success("保存成功");
    }

    @Operation(summary = "查询Redis中所有的GPS信息")
    @GetMapping("/getAll")
    public ActionResult<Map<String, GpsInfoEntity>> getAllFromRedis() {
        Map<String, GpsInfoEntity> result = new HashMap<>();

        // 使用 pattern 查询所有匹配的key
        Set<String> keys = redisTemplate.keys("gps_info:*");
        if (keys != null && !keys.isEmpty()) {
            List<Object> values = redisTemplate.opsForValue().multiGet(keys);

            // 匹配key和value
            Iterator<String> keyIterator = keys.iterator();
            int index = 0;
            while (keyIterator.hasNext() && index < values.size()) {
                String key = keyIterator.next();
                if (values.get(index) != null) {
                    Object value = values.get(index);
                    GpsInfoEntity entity = convertToGpsInfoEntity(value);
                    if (entity != null) {
                        String userId = key.replace("gps_info:", "");
                        result.put(userId, entity);
                    }
                }
                index++;
            }
        }

        return ActionResult.success(result);
    }

    @Operation(summary = "根据userId和时间段查询GPS信息")
    @GetMapping("/getAllGpsInfo")
    public ActionResult<List<GpsInfoEntity>> getAllGpsInfo(
            @Parameter(description = "用户ID") @RequestParam(required = false) List<String> userId,
            @Parameter(description = "开始时间") @RequestParam(required = false) Long startTime,
            @Parameter(description = "结束时间") @RequestParam(required = false) Long endTime) {

        List<GpsInfoEntity> result;

        // 无论是否提供userId，都从数据库查询数据
        result = gpsInfoService.queryGpsInfoByConditions(userId, startTime, endTime);

        return ActionResult.success(result);
    }
    @Operation(summary = "围栏查询")
    @PostMapping("/fenceQuery")
    public ActionResult<?> fenceQuery(@RequestParam String startTime,@RequestParam String endTime,@RequestParam String name,@RequestParam String currentPage,@RequestParam String pageSize) {
        IPage<GpsInfoVo> list = gpsInfoService.fenceQuery(startTime,endTime,name,currentPage,pageSize);
        return ActionResult.success(list);
    }
    @Operation(summary = "定位统计")
    @PostMapping("/positioningStatistics")
    public ActionResult<?> positioningStatistics(@RequestParam String name) {
        List<GpsInfoVo> list = gpsInfoService.positioningStatistics(name);
        return ActionResult.success(list);
    }

//    @Operation(summary = "查人员定位")
//    @PostMapping("/getListByPerson")
//    public ActionResult<?> getListByPerson(@RequestParam String startTime,@RequestParam String endTime,@RequestParam String name,@RequestParam String currentPage,@RequestParam String pageSize) {
//        IPage<GpsInfoVo> listByPerson = gpsInfoService.getListByPerson(startTime, endTime, name,currentPage,pageSize);
//        return ActionResult.success(listByPerson);
//    }
    @Operation(summary = "查准组定位")
    @PostMapping("/getListByGroup")
    public ActionResult<?> getListByGroup(@RequestParam String startTime,@RequestParam String endTime,@RequestParam String name) {
        List<GpsInfoVo2> listByPerson = gpsInfoService.getListByGroup(startTime, endTime, name);
        return ActionResult.success(listByPerson);
    }

    @Operation(summary = "人员定位信息导出")
    @PostMapping("/exportExcelByPerson")
    public ActionResult<?> exportExcelByPerson(@RequestParam String startTime,@RequestParam String endTime,@RequestParam String name) {
        DownloadVO downloadVO = gpsInfoService.exportExcelByPerson(startTime, endTime, name);
        return ActionResult.success(downloadVO);
    }
    @Operation(summary = "群组定位信息导出")
    @PostMapping("/exportExcelByGroup")
    public ActionResult<?> exportExcelByGroup(@RequestParam String startTime,@RequestParam String endTime) {
        DownloadVO downloadVO = gpsInfoService.exportExcelByGroup(startTime, endTime);
        return ActionResult.success(downloadVO);
    }

    @PostMapping("/deleteDataOne")
    public ActionResult<?> deleteDataOne(@RequestBody @Valid GpsInfoEntity gpsInfoEntity) {
        LambdaQueryWrapper<GpsInfoEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(GpsInfoEntity::getType, gpsInfoEntity.getType());
        queryWrapper.eq(GpsInfoEntity::getRemark1, gpsInfoEntity.getRemark1());
        queryWrapper.eq(GpsInfoEntity::getRemark2, gpsInfoEntity.getRemark2());
        queryWrapper.eq(GpsInfoEntity::getLng, gpsInfoEntity.getLng());
        queryWrapper.eq(GpsInfoEntity::getLat, gpsInfoEntity.getLat());
        queryWrapper.eq(GpsInfoEntity::getTime, gpsInfoEntity.getTime());

        boolean b = gpsInfoService.remove(queryWrapper);
        if (b){
            return ActionResult.success("删除成功");
        }else{
            return ActionResult.fail("删除失败");
        }
    }

    @Operation(summary = "人员定位连表查询")
    @PostMapping("/getListByPerson")
    public ActionResult<?> getListWithJoinTable(
            @RequestParam String startTime,
            @RequestParam String endTime,
            @RequestParam String name,
            @RequestParam String currentPage,
            @RequestParam String pageSize) {

        // 如果需要分页，可以在这里处理分页逻辑
        // 或者将分页参数传递给service层处理

        IPage<GpsInfoVo> list = gpsInfoService.getListWithJoinTable(
                startTime, endTime, name, currentPage, pageSize);
        return ActionResult.success(list);
    }




    //redis数据转化
    private GpsInfoEntity convertToGpsInfoEntity(Object value) {
        if (value instanceof GpsInfoEntity) {
            return (GpsInfoEntity) value;
        } else if (value instanceof LinkedHashMap) {
            return JsonUtil.getJsonToBean(value, GpsInfoEntity.class);
        }
        return null;
    }





}
